import { login, getUserInfoApi, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    // console.log(data)
    setToken(data)
    state.token = data
  },
  setUserInfo(state, data) {
    console.log(data)
    state.userInfo = data
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(store, data) {
    const res = await login(data)
    // console.log(res)
    store.commit('setToken', res)
    localStorage.setItem('loginTime', Date.now())
  },
  async getUserInfoApi(store) {
    const res = await getUserInfoApi()
    const Detail = await getUserDetailById(res.userId)
    store.commit('setUserInfo', { ...res, ...Detail })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
